package com.swust.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.swust.common.Conf.LOGIN_USER;

/**
 * 判断用户是否登陆
 */
@WebFilter(filterName = "AuthFilter", urlPatterns = "/*")
public class AuthFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 判断用户是否登陆
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String loginUser = (String) request.getSession().getAttribute(LOGIN_USER); // 提取session中的用户名

        String uri = request.getRequestURI();
        //System.out.println(request.getContextPath()+"/view/index.jsp");
        //System.out.println(uri);
        if (loginUser == null) {        // 用户未操作
            if(uri.equals(request.getContextPath()+"/view/index.jsp") || uri.equals(request.getContextPath()+"/view/regist.jsp")
                    || uri.equals(request.getContextPath()+"/") || uri.equals(request.getContextPath()+"/RegistServlet")
                    || uri.equals(request.getContextPath()+"/LoginServlet")){  //如果此时页面已经为登陆页面或注册页面则无需过滤
                chain.doFilter(req,resp);
                return;
            }
            response.sendRedirect(request.getContextPath() + "/view/index.jsp?flag=1"); // 未登录，系统自动跳转到登陆页面
            return;
        } else {
            chain.doFilter(req, resp);
            return;
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
